package com.bt.lms.ui.action.registration.stu;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.RegStuBizTypeConstant;
import com.bt.lms.entity.RegStuInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.ui.page.stu.PageMainStudentList;
import com.bt.lms.ui.page.stu.vo.RegistrationStuVo;
import com.bt.lms.ui.page.stu.PageAddStuInfo;
import com.bt.lms.ui.page.common.action.pageenp.ApplyStuLabAction;

import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;

import java.time.LocalDate;

/**
 * 添加学生信息界面保存按钮事件
 *
 * @author 朱传博
 */
public class PageAddStuSaveBtnAction implements EventHandler {

    /**
     * 添加学生信息界面
     */

    public static PageAddStuInfo pageAddStuInfo;


    @Override
    public void handle(Event event) {

        //1.获取用户输入
        RegistrationStuVo registrationStuVo = getInPrams();
        //2.验证用户输入
        String validDateMsg = validateInParam(registrationStuVo);


        //3.组包
        byte[] bytes = null;
        if (null == validDateMsg) {
            //验证通过，组包
            bytes = handleReqMsg(registrationStuVo);


        } else {
            //提示框
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(validDateMsg);
            alert.showAndWait();


            //提示程序终止
            return;

        }

        //4.获取网络
        Socket socket = getNet();

        //5.发送消息
        boolean sendReqMsg = sendReqMsg(socket, bytes);


        //返回主界面
        PageMainStudentList pageMainStudentList = new PageMainStudentList();
        Pane pane = ApplyStuLabAction.pageSkipInfo.getPane();
        Integer index = ApplyStuLabAction.pageSkipInfo.getIndex();
        pane.getChildren().set(index, pageMainStudentList);

    }

    /**
     * 发送请求消息
     *
     * @param socket 网
     * @param bytes  bytes数组
     * @return 是否成功
     */
    private boolean sendReqMsg(Socket socket, byte[] bytes) {

        try {
            OutputStream out = socket.getOutputStream();
            out.write(bytes);
            out.flush();


            byte[]buffer = new byte[1024];

            InputStream in = socket.getInputStream();
            in.read(buffer);
            in.close();

            out.close();
            socket.close();



        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }




    /**
     * 获取网络
     *
     * @return
     */
    private Socket getNet() {

        String ip = "127.0.0.1";
        Integer port = 8888;
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return socket;

    }

    /**
     * 组包
     *
     * @param registrationStuVo 报名学员vo
     * @return
     */
    private byte[] handleReqMsg(RegistrationStuVo registrationStuVo) {


        //请求消息
        ReqMsg reqMsg = new ReqMsg();

        //报名学员信息
        RegStuInfo regStuInfo = new RegStuInfo();

        //业务类型
        reqMsg.setBizType(RegStuBizTypeConstant.STU_REG_INFO_ADD);

        //请求id时间戳
        long l = System.currentTimeMillis();
        reqMsg.setReqId(l);


        try {
            //将vo转成entity
            BeanUtils.copyProperties(regStuInfo, registrationStuVo);
            regStuInfo.setReqWay(1);
            regStuInfo.setWechat("ZCB1120..");


            String regStuStr = JSON.toJSONString(regStuInfo);


            //把数据带走
            reqMsg.setData(regStuStr);


        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        //需要转成byte 总数组 掉方法

        byte[] bytes = reqMsg.toBytes();


        return bytes;
    }


    /**
     * 验证用户输入
     *
     * @param registrationStuVo 用户输入的消息
     * @return 验证的结果消息
     */
    private String validateInParam(RegistrationStuVo registrationStuVo) {

        String msg = "";
        //报名编号
        String registrationNo = registrationStuVo.getRegistrationCode();

        String registrationNoLen = "报名编号长度在1-32个字符之间\r\n";
        if (registrationNo.length() > 32) {
            msg += registrationNoLen;
        }

        //姓名
        String name = registrationStuVo.getName();
        String nameNullMsg = "姓名必须填写\r\n";
        String nameLenMsg = "姓名长度在1-32个字符之间\r\n";

        if (name.equals("")) {
            msg += nameNullMsg;
        }
        if (name.length() > 32) {
            msg += nameLenMsg;
        }


        //证件号码
        String idNo = registrationStuVo.getCredNo();
        String idNoNullMsg = "证件号码必须填写\r\n";
        String idNoLen = "证件号码必须18位\r\n";
        if (idNo.equals("")) {//如果空
            msg += idNoNullMsg;
        }


        if (!(idNo.length() == 18)) {//证件号码不等于18

            msg += idNoLen;
        }


        //电子邮箱
        String email = registrationStuVo.getEmail();
        String emailNullMsg = "电子邮箱必须填写\r\n";
        String emailLenMsg = "电子邮箱不能超过32位\r\n";
        if (email.equals("")) {
            msg += emailNullMsg;
        }
        if (email.length() > 32) {
            msg += emailLenMsg;
        }


        //所属招生计划
        String enpPlan = registrationStuVo.getEnpPlan();
        String enpPlanNull = "所属招生计划必须填写\r\n";
        if (enpPlan.equals("")) {
            msg += enpPlanNull;

        }

        //移动电话
        String mobilePhone = registrationStuVo.getMobilePhone();
        String mobilePhoneNull = "移动电话不能为空\r\n";
        String mobilePhoneNo = "移动电话必须是数字\r\n";
        String mobileLen = "移动电话需11位\r\n";


        if (mobilePhone.equals("")) {
            msg += mobilePhoneNull;
        }
        try {
            long l = Long.parseLong(mobilePhone);//需数字
        } catch (NumberFormatException e) {
            msg += mobilePhoneNo;
        }
        if (!(mobilePhone.length() == 11)) {//不等于11位
            msg += mobileLen;
        }

        //出生日期
        LocalDate birthday = registrationStuVo.getBirthday();
        String birthdayNull = "出生日期必填\r\n";
        String birthdayRange = "出生日期必须在当前日期150之内\r\n";
        if (birthday == null) {//如果为空
            msg += birthdayNull;
        } else {
            LocalDate now = LocalDate.now();//现在的时间
            int nowYear = now.getYear();//现在年
            int birthdayYear = birthday.getYear();//获取到出生年
            if (birthdayYear > nowYear || nowYear - birthdayYear > 150) {
                msg += birthdayRange;

            }

        }

        //qq部分
        String qq = registrationStuVo.getQq();
        String qqNull = "qq必填\r\n";
        String qqNo = "qq必须是数字\r\n";
        String qqLen = "qq长度超过10位";

        if (qq.equals("")) { //qq为空
            msg += qqNull;
        }
        try {
            long l = Long.parseLong(qq);//必须是数字
        } catch (NumberFormatException e) {
            msg += qqNo;

        }
        if (qq.length() > 10) {
            msg += qqLen;
        }

        //微信部分
        String weChat = registrationStuVo.getWeChat();
        String weChatNull = "微信必填";
        if (weChat.equals("")) {
            msg += weChatNull;

        }


        //返回结果
        if ("".equals(msg)) {
            return null;

        } else {
            return msg;
        }

    }

    /**
     * 获取用户输入的内容
     */
    private RegistrationStuVo getInPrams() {


        TextField applyNumTF = (TextField) pageAddStuInfo.lookup("#applyNumTF");
        TextField nameTF = (TextField) pageAddStuInfo.lookup("#nameTF");
        ComboBox genderCB = (ComboBox) pageAddStuInfo.lookup("#genderCB");
        TextField IDNumTF = (TextField) pageAddStuInfo.lookup("#IDNumTF");
        TextField emailTF = (TextField) pageAddStuInfo.lookup("#emailTF");
        //封装成VO对象
        RegistrationStuVo registrationStuVo = new RegistrationStuVo();


        String applyNumStr = applyNumTF.getText().trim();//获取到输入的内容并且去掉无效空格
        registrationStuVo.setRegistrationCode(applyNumStr);

        String nameStr = nameTF.getText().trim();//获取姓名输入的内容并且去掉无效空格
        registrationStuVo.setName(nameStr);

        String value = (String) genderCB.getValue();
        Integer gender = -1;
        switch (value) {
            case "男":
                gender = 1;
                break;
            case "女":
                gender = 2;
                break;
        }
        registrationStuVo.setGender(gender);

        String IDNumStr = IDNumTF.getText().trim();//身份证号
        registrationStuVo.setCredNo(IDNumStr);

        String emailStr = emailTF.getText().trim();//电子邮箱
        registrationStuVo.setEmail(emailStr);


        TextField ofEnPTF = (TextField) pageAddStuInfo.lookup("#ofEnPTF");//所属招生计划
        String ofEnpStr = ofEnPTF.getText().trim();
        registrationStuVo.setEnpPlan(ofEnpStr);


        TextField movePhoneTF = (TextField) pageAddStuInfo.lookup("#movePhoneTF");//移动电话
        String movePhoneStr = movePhoneTF.getText().trim();
        registrationStuVo.setMobilePhone(movePhoneStr);


        DatePicker birthdayDP = (DatePicker) pageAddStuInfo.lookup("#birthdayDP");//出生日期
        LocalDate birthdayDPValue = birthdayDP.getValue();
        registrationStuVo.setBirthday(birthdayDPValue);

        ComboBox IDTpeCB = (ComboBox) pageAddStuInfo.lookup("#IDTpeCB");//证件类型
        String IDTpeCBValue = (String) IDTpeCB.getValue();
        Integer certType = -1;
        switch (IDTpeCBValue) {
            case "身份证":
                certType = 1;
                break;

            case "军官证":
                certType = 2;
                break;

        }
        registrationStuVo.setCredType(certType);

        //qq部分
        TextField qqTF = (TextField) pageAddStuInfo.lookup("#qqTF");
        String qqStr = qqTF.getText().trim();
        registrationStuVo.setQq(qqStr);


        //微信部分
        TextField weChatTF = (TextField) pageAddStuInfo.lookup("#weChatTF");
        String weCharStr = weChatTF.getText().trim();
        registrationStuVo.setWeChat(weCharStr);


        return registrationStuVo;
    }


    public PageAddStuInfo getPageAddStuInfo() {
        return pageAddStuInfo;
    }

    public void setPageAddStuInfo(PageAddStuInfo pageAddStuInfo) {
        this.pageAddStuInfo = pageAddStuInfo;
    }
}
